/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.service.impl;

import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.util.OperateTest;
import com.koron.common.web.Util;
import com.koron.purpose.bean.SafetyDirectorAssessmentBean;
import com.koron.purpose.domain.ScoreAssessment;
import com.koron.purpose.domain.SinceAssessment;
import com.koron.purpose.mapper.SafetyDirectorAssessmentMapper;
import com.koron.purpose.mapper.ScoreAssessmentMapper;
import com.koron.purpose.mapper.SinceAssessmentMapper;
import com.koron.purpose.service.api.SafetyDirectorAssessmentService;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.swan.bean.MessageBean;

import java.util.*;

@PropertySource({"classpath:remarks.properties"})
@Service
public class SafetyDirectorAssessmentServiceImpl implements SafetyDirectorAssessmentService {


	private final static Logger logger= LoggerFactory.getLogger(SafetyDirectorAssessmentServiceImpl.class);
	private static final String[] TYPE_1 = new String[] {"站长", "部门分管安全领导", "安全部经理", "安全部总经理"};
	private static final String[] TYPE_2 = new String[] {"部门分管安全领导", "公司总经理", "公司董事长", "安全部经理", "安全部总经理"};
	private static final String[] TYPE_3 = new String[] {"部门分管安全领导", "片区总经理", "安全部经理", "安全部总经理"};
	//安全部总经理
	@Value("${safety_general_manager_code}")
	private String nextCode;
	@Value("${safety_general_manager}")
	private String nextName;	
	
	@Autowired
	private Util util;
	
	@SuppressWarnings({ "deprecation", "rawtypes" })
	@Override
	public MessageBean<?> insert(SafetyDirectorAssessmentBean bean, StaffBean user) {
		MessageBean<String> msg = MessageBean.create(0, "SUCCESS", String.class);
		Map checkMap = addCheck(bean);
		int code = (int) checkMap.get("code");
        String description = (String) checkMap.get("description");
        if(code != 0){
        	msg.setCode(code);
        	msg.setDescription(description);
        	return msg;
        }
		SessionFactory factory = new SessionFactory();
		try {
			bean.setAddTime(new Date());
			bean.setAddUser(user.getCode());
			bean.setAddUserName(user.getName());
			bean.setUpdateTime(new Date());
			bean.setUpdateUser(user.getCode());
			bean.setUpdateUserName(user.getName());
			bean.setId(DefaultIdGenerator.getInstance().generateLongId());
			bean.setFstatusflag(0);//草稿
			bean.setFlagNow(0);
			List<SinceAssessment> saList = bean.getSaList();  //自评加分项
			for (SinceAssessment sa : saList) {
				sa.setId(DefaultIdGenerator.getInstance().generateLongId());
				sa.setAssessmentId(bean.getId());
			}
			SafetyDirectorAssessmentMapper mppaer = factory.getMapper(SafetyDirectorAssessmentMapper.class);
			SinceAssessmentMapper saMapper = factory.getMapper(SinceAssessmentMapper.class);
			if(!saList.isEmpty()){
				saMapper.batchInsert(saList);
			}
			mppaer.insert(bean);
			msg.setData(bean.getId());
			factory.close();
		} catch (Exception e) {
			factory.close(false);
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
			return msg;
		}
		return msg;
	}

	@SuppressWarnings({ "rawtypes", "deprecation" })
	@Override
	public MessageBean<?> update(SafetyDirectorAssessmentBean bean, StaffBean user) {
		MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
		if(StringUtils.isEmpty(bean.getId())){
			msg.setCode(35002);
			msg.setDescription("参数校验异常");
			return msg;
		}
		Map checkMap = addCheck(bean);
		int code = (int) checkMap.get("code");
        String description = (String) checkMap.get("description");
        if(code != 0){
        	msg.setCode(code);
        	msg.setDescription(description);
        	return msg;
        }
		SessionFactory factory = new SessionFactory();
		try {
			bean.setUpdateTime(new Date());
			bean.setUpdateUser(user.getCode());
			bean.setUpdateUserName(user.getName());
			List<SinceAssessment> saList = bean.getSaList();  //自评加分项
			for (SinceAssessment sa : saList) {
				sa.setId(DefaultIdGenerator.getInstance().generateLongId());
				sa.setAssessmentId(bean.getId());
			}
			SafetyDirectorAssessmentMapper mppaer = factory.getMapper(SafetyDirectorAssessmentMapper.class);
			SinceAssessmentMapper saMapper = factory.getMapper(SinceAssessmentMapper.class);
			//删除原来的自评项
			saMapper.delete(bean.getId());
			if(!saList.isEmpty()){
				saMapper.batchInsert(saList);
			}
			mppaer.update(bean);
			factory.close();
		} catch (Exception e) {
			factory.close(false);
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
			return msg;
		}
		return msg;
	}

	@SuppressWarnings("deprecation")
	@Override
	public MessageBean<?> delete(String id) {
		MessageBean<?> msg = MessageBean.create(0, "success", void.class);
		SafetyDirectorAssessmentBean bean = queryById("",id);
		if(bean == null){
			msg.setCode(35002);
			msg.setDescription("参数校验异常");
			return msg;
		}
		if(bean.getFstatusflag() != 0){
			msg.setCode(35002);
			msg.setDescription("非草稿单据不能删除");
			return msg;
		}
		SessionFactory factory = new SessionFactory();
		try{
			factory.getMapper(SafetyDirectorAssessmentMapper.class).delete(id);
			factory.getMapper(SinceAssessmentMapper.class).delete(id);
			factory.close();
		} catch (Exception e) {
			factory.close(false);
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
		}
		return msg;
	}

	@Override
	public MessageBean<?> details(String userCode,String id) {
		MessageBean<SafetyDirectorAssessmentBean> msg = MessageBean.create(0, "success", SafetyDirectorAssessmentBean.class);
		SafetyDirectorAssessmentBean bean = queryById(userCode,id);
		msg.setData(bean);
		return msg;
	}

	@SuppressWarnings({ "deprecation", "rawtypes", "unchecked" })
	@Override
	public MessageBean<?> list(String userCode,String corpCode,String month, Integer corpType, String staffName,
			Integer assessmentType, Integer fstatusflag, Integer page, Integer pageSize) {
		MessageBean<DataBean> msg= MessageBean.create(0,"SUCCESS", DataBean.class);
		if(StringUtils.isEmpty(corpCode) || StringUtils.isEmpty(userCode)){
			msg.setCode(35002);
			msg.setDescription("参数校验异常");
			return msg;
		}
		Integer totalPage = null;
	    Integer totalNumber = null;
	    Integer start = null;
	    Integer end = null;
	    if (null!=page && pageSize!=null){
            if (page >0 && pageSize > 0){
            }else{
            	//第一页 10条数据
            	page =1;
            	pageSize=10;
            }
            start=(page<=1)?0:(page-1)*pageSize;
            end = pageSize;
        }
	    if(staffName != null){
	    	staffName = "%" + staffName +"%";
	    }
	    try(SessionFactory factory = new SessionFactory();){
	    	String user = userCode;
			if(operateTest.isAdmin(userCode)){
				user = null;
			}
	    	totalNumber = factory.getMapper(SafetyDirectorAssessmentMapper.class).count(corpCode, user, month, corpType, staffName, assessmentType, fstatusflag);
	    	if(start != null && end != null){
				totalPage = (totalNumber+pageSize-1)/pageSize;
			}else{
				totalPage = 1;
				page = totalPage;
				pageSize = totalNumber;
			}
	    	DataBean data = new DataBean();
			data.setList(queryList(corpCode, userCode, month, corpType, staffName, assessmentType, fstatusflag, start, end));
			data.setPageNo(page);
			data.setPageSize(pageSize);
			data.setTotalNumber(totalNumber);
			data.setTotalPage(totalPage);
			msg.setData(data);
	    } catch (Exception e) {
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
			return msg;
		}
		return msg;
	}
	
	
	@SuppressWarnings("deprecation")
	@Override
	public MessageBean<?> submit(String id, String nextStaff) {
		MessageBean<?> msg = MessageBean.create(0, "success", void.class);
		if(StringUtils.isEmpty(id)){
			msg.setCode(35002);
			msg.setDescription("参数校验异常");
			return msg;
		}
		SessionFactory factory = new SessionFactory();
		try{
			SafetyDirectorAssessmentBean bean = factory.getMapper(SafetyDirectorAssessmentMapper.class).queryById(id);
			if(bean == null){
				factory.close(false);
				msg.setCode(35002);
				msg.setDescription("参数校验异常");
				return msg;
			}
			if(bean.getFstatusflag()!=0){
				factory.close(false);
				msg.setCode(35002);
				msg.setDescription("单据已提交");
				return msg;
			}
			bean.setFlagNow(1); //第一个打分节点
			bean.setFstatusflag(1);//审批中
			bean.setScoreStaffs(nextStaff);
			factory.getMapper(SafetyDirectorAssessmentMapper.class).updateScore(bean);
			factory.close();
		} catch (Exception e) {
			factory.close(false);
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
		}
		return msg;
	}

	@SuppressWarnings({ "deprecation", "unchecked" })
	@Override
	public MessageBean<?> score(String staffCode,String staffName,String note,Float score, String id,String nextStaff) {
		MessageBean<?> msg = MessageBean.create(0, "success", void.class);
		if(StringUtils.isEmpty(id) || StringUtils.isEmpty(staffCode)|| StringUtils.isEmpty(staffName)|| score==null){
			msg.setCode(35002);
			msg.setDescription("参数校验异常");
			return msg;
		}
		SessionFactory factory = new SessionFactory();
		try{
			SafetyDirectorAssessmentBean bean = queryById(staffCode,id);
			if(bean == null){
				factory.close(false);
				msg.setCode(35002);
				msg.setDescription("单据id无效");
				return msg;
			}
			if(bean.getFstatusflag() == 2){
				factory.close();
				msg.setCode(35002);
				msg.setDescription("单据打分已完成");
				return msg;
			}
			String codes = bean.getScoreStaffs();
			if(codes == null){
				factory.close();
				msg.setCode(35002);
				msg.setDescription("无打分权限");
				return msg;
			}
			String[] array = codes.split(",");
			List<String> codeList = new ArrayList<>(Arrays.asList(array));
			int flag = codeList.lastIndexOf(staffCode);
			if(flag == -1){
				factory.close();
				msg.setCode(35002);
				msg.setDescription("无打分权限");
				return msg;
			}
			int now = bean.getFlagNow();
			if(flag+1 != now){
				factory.close();
				msg.setCode(35002);
				msg.setDescription("已完成打分");
				return msg;
			}
			
			//保存打分操作
			ScoreAssessment sa = new ScoreAssessment();
			sa.setAssessmentId(id);
			sa.setId(DefaultIdGenerator.getInstance().generateLongId());
			sa.setNote(note);
			sa.setScore(score);
			sa.setScoreDate(new Date());
			sa.setScoreProject(bean.getNowNodeName());
			sa.setSerial(now);
			sa.setStaffCode(staffCode);
			sa.setStaffName(staffName);
			factory.getMapper(ScoreAssessmentMapper.class).insert(sa);
			
			//修改表单信息
			int flagNumber = bean.getFlagNumber();
			if(now == flagNumber){
				//打分已全部完成
				bean.setFstatusflag(2);
				//计算分数
				List<ScoreAssessment> scoreList = factory.getMapper(ScoreAssessmentMapper.class).queryList(id,now);
				Float total = 0f; 
				for (ScoreAssessment scoreBean : scoreList) {
					Float temp = scoreBean.getScore() == null?0f:scoreBean.getScore();
					total+=temp;
				}
				bean.setAssessmentScore(bean.getAssessmentScore()+total);
			}else{
				if(StringUtils.isEmpty(nextStaff)){
					factory.close(false);
					msg.setCode(35002);
					msg.setDescription("请选择下一位评分人");
					return msg;
				}
				now++;
				codes = codes+"," + nextStaff;
				bean.setScoreStaffs(codes);
			}
			bean.setFlagNow(now);
			factory.getMapper(SafetyDirectorAssessmentMapper.class).updateScore(bean);
			factory.close();
		} catch (Exception e) {
			factory.close(false);
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
		}
		return msg;
	}
	
	@Autowired
	private OperateTest operateTest;
	
	@SuppressWarnings("deprecation")
	public List<SafetyDirectorAssessmentBean> queryList(String corpCode, String addUser, String month, Integer corpType, String staffName,
			Integer assessmentType, Integer fstatusflag, Integer start, Integer row){
		List<SafetyDirectorAssessmentBean> list = new ArrayList<>();
		try(SessionFactory factory = new SessionFactory();) {
			String userCode = addUser;
			if(operateTest.isAdmin(userCode)){
				userCode = null;
			}
			list = factory.getMapper(SafetyDirectorAssessmentMapper.class).list(corpCode, userCode, month, corpType, staffName, assessmentType, fstatusflag, start, row);
			for (SafetyDirectorAssessmentBean bean : list) {
				String str = bean.getScoreStaffs()==null?"":bean.getScoreStaffs();
				if(bean.getFstatusflag()!=2 && str.endsWith(addUser)){
					bean.setCanScore(1); //打分
				}else{
					bean.setCanScore(0);
				}
			}
		}
		return list;
	}
	@SuppressWarnings({ "deprecation", "unchecked" })
	public SafetyDirectorAssessmentBean queryById(String userCode,String id){
		SafetyDirectorAssessmentBean bean = new SafetyDirectorAssessmentBean();
		try(SessionFactory factory = new SessionFactory();) {
			bean = factory.getMapper(SafetyDirectorAssessmentMapper.class).queryById(id);
			if(bean != null){
				bean.setSaList(factory.getMapper(SinceAssessmentMapper.class).queryByAid(id));
				String staffs = bean.getScoreStaffs()==null?"":bean.getScoreStaffs();
				if(bean.getFstatusflag()!=2 && staffs.endsWith(userCode)){
					bean.setCanScore(1); //打分
				}else{
					bean.setCanScore(0);
				}
				if(bean.getFstatusflag() == 0){
					bean.setNowNodeName("草稿");
					if(1 == bean.getCorpType()){
						//供水
						bean.setNextNodeName(TYPE_1[0]);
					}else if(2 == bean.getCorpType()){
						//水务
						bean.setNextNodeName(TYPE_2[0]);
					}else if(3 == bean.getCorpType()){
						//片区
						bean.setNextNodeName(TYPE_3[0]);
					}
					return bean;
				}
				int nowFlag = bean.getFlagNow();
				if(nowFlag == 0){//草稿
					bean.setNowNodeName("提交");
					if(1 == bean.getCorpType()){
						//供水
						bean.setNextNodeName(TYPE_1[0]);
					}else if(2 == bean.getCorpType()){
						//水务
						bean.setNextNodeName(TYPE_2[0]);
					}else if(3 == bean.getCorpType()){
						//片区
						bean.setNextNodeName(TYPE_3[0]);
					}
				}
				if(nowFlag > 0 && nowFlag < bean.getFlagNumber()){ //评分中
					if(1 == bean.getCorpType()){
						//供水
						bean.setNextNodeName(TYPE_1[nowFlag]);
						bean.setNowNodeName(TYPE_1[nowFlag-1]);
					}else if(2 == bean.getCorpType()){
						//水务
						bean.setNextNodeName(TYPE_2[nowFlag]);
						bean.setNowNodeName(TYPE_2[nowFlag-1]);
					}else if(3 == bean.getCorpType()){
						//片区
						bean.setNextNodeName(TYPE_3[nowFlag]);
						bean.setNowNodeName(TYPE_3[nowFlag-1]);
					}
					if("安全部总经理".equals(bean.getNextNodeName())){
						bean.setNextStaffCode(nextCode);
						bean.setNextStaffName(nextName);
					}
				}
				if(nowFlag == bean.getFlagNumber()){
					if(1 == bean.getCorpType()){
						//供水
						bean.setNowNodeName(TYPE_1[nowFlag-1]);
					}else if(2 == bean.getCorpType()){
						//水务
						bean.setNowNodeName(TYPE_2[nowFlag-1]);
					}else if(3 == bean.getCorpType()){
						//片区
						bean.setNowNodeName(TYPE_3[nowFlag-1]);
					}
				}
				String[] array = staffs.split(",");
				List<String> codeList = new ArrayList<>(Arrays.asList(array));
				String nowStaff = codeList.get(nowFlag-1);
				MessageBean<?> staffMsg = util.staff(nowStaff, 0);
				if(staffMsg.getCode() == 0 && staffMsg.getData() != null){
					StaffBean sbean = (StaffBean) ((List)staffMsg.getData()).get(0);
					if(sbean != null){
						nowStaff = sbean.getName();
					}
				}
				bean.setNowStaff(nowStaff);
				int index = codeList.lastIndexOf(userCode);
				index++;
				if(operateTest.isAdmin(userCode)){
					index = 99;
				}
				bean.setScoreList(factory.getMapper(ScoreAssessmentMapper.class).queryList(id, index));
			}
		}
		return bean;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private Map addCheck(SafetyDirectorAssessmentBean bean){
		Map map = new HashMap();
		if(bean == null){
			map.put("code", 35002);
    		map.put("description", "请填写考核信息");
    		return map;
		}
		if(StringUtils.isEmpty(bean.getCorpCode())){
			map.put("code", 35002);
    		map.put("description", "公司不能为空");
    		return map;
		}
		if(StringUtils.isEmpty(bean.getStaffCode())){
			map.put("code", 35002);
    		map.put("description", "考核人不能为空");
    		return map;
		}
		if(bean.getCorpType() == null){
			map.put("code", 35002);
    		map.put("description", "公司类型不能为空");
    		return map;
		}
		if(bean.getAssessmentType() == null){
			map.put("code", 35002);
    		map.put("description", "考核类型不能为空");
    		return map;
		}
		if(StringUtils.isEmpty(bean.getMonth())){
			map.put("code", 35002);
    		map.put("description", "考核年月不能为空");
    		return map;
		}
		if(bean.getBasicScore() == null){
			map.put("code", 35002);
    		map.put("description", "基准分不能为空");
    		return map;
		}
		if(1 == bean.getCorpType()){
			//供水
			bean.setFlagNumber(TYPE_1.length);
		}else if(2 == bean.getCorpType()){
			//水务
			bean.setFlagNumber(TYPE_2.length);
		}else if(3 == bean.getCorpType()){
			//片区
			bean.setFlagNumber(TYPE_3.length);
		}else{
			map.put("code", 35002);
    		map.put("description", "公司类型错误");
    		return map;
		}
		//自评分
		List<SinceAssessment> saList = bean.getSaList();
		int row = 1;
		Float sinceScore = bean.getBasicScore();
		for (SinceAssessment sa : saList) {
			if(StringUtils.isEmpty(sa.getScoreProject())){
				map.put("code", 35002);
				map.put("description", "自评：行+"+row+"评分项目不能为空");
	    		return map;
			}
			if(StringUtils.isEmpty(sa.getScoreBasis())){
				map.put("code", 35002);
				map.put("description", "自评：行+"+row+"评分依据不能为空");
	    		return map;
			}
			if(sa.getScore() == null){
				map.put("code", 35002);
				map.put("description", "自评：行+"+row+"评分不能为空");
	    		return map;
			}
			sinceScore+=sa.getScore();
			row++;
		}
		bean.setSinceScore(sinceScore);
		bean.setAssessmentScore(bean.getBasicScore()+sinceScore);
		map.put("code", 0);
		map.put("description", "校验成功");
		return map;
	}
}
